/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cw.controller;

import cw.controller.exceptions.NonexistentEntityException;
import cw.controller.exceptions.PreexistingEntityException;
import cw.entity.Question;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import cw.entity.Puzzle;
import java.util.ArrayList;
import java.util.logging.Logger;

/**
 *
 * @author VinhTC
 */
public class QuestionJpaController {

    public QuestionJpaController() {
        emf = Persistence.createEntityManagerFactory("CrossWordsAdminPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Question question) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Puzzle puzzle = question.getPuzzle();
            if (puzzle != null) {
                puzzle = em.getReference(puzzle.getClass(), puzzle.getPuzzleId());
                question.setPuzzle(puzzle);
            }
            em.persist(question);
            if (puzzle != null) {
                puzzle.getQuestionList().add(question);
                puzzle = em.merge(puzzle);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findQuestion(question.getQuestionId()) != null) {
                throw new PreexistingEntityException("Question " + question + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Question question) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Question persistentQuestion = em.find(Question.class, question.getQuestionId());
            Puzzle puzzleOld = persistentQuestion.getPuzzle();
            Puzzle puzzleNew = question.getPuzzle();
            if (puzzleNew != null) {
                puzzleNew = em.getReference(puzzleNew.getClass(), puzzleNew.getPuzzleId());
                question.setPuzzle(puzzleNew);
            }
            question = em.merge(question);
            if (puzzleOld != null && !puzzleOld.equals(puzzleNew)) {
                puzzleOld.getQuestionList().remove(question);
                puzzleOld = em.merge(puzzleOld);
            }
            if (puzzleNew != null && !puzzleNew.equals(puzzleOld)) {
                puzzleNew.getQuestionList().add(question);
                puzzleNew = em.merge(puzzleNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = question.getQuestionId();
                if (findQuestion(id) == null) {
                    throw new NonexistentEntityException("The question with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Question question;
            try {
                question = em.getReference(Question.class, id);
                question.getQuestionId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The question with id " + id + " no longer exists.", enfe);
            }
            Puzzle puzzle = question.getPuzzle();
            if (puzzle != null) {
                puzzle.getQuestionList().remove(question);
                puzzle = em.merge(puzzle);
            }
            em.remove(question);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Question> findQuestionEntities() {
        return findQuestionEntities(true, -1, -1);
    }

    public List<Question> findQuestionEntities(int maxResults, int firstResult) {
        return findQuestionEntities(false, maxResults, firstResult);
    }

    private List<Question> findQuestionEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Question.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Question findQuestion(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Question.class, id);
        } finally {
            em.close();
        }
    }

    public int getQuestionCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Question> rt = cq.from(Question.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    /**
     * getQuestionByPuzzleId
     * @param puzzleId
     * @return List<Question
     */
    public List<Question> getQuestionByPuzzleId(int puzzleId) {
        List<Question> lst = new ArrayList<Question>();
        List<Question> temp = new ArrayList<Question>();
        try {
//            Query query = getEntityManager().createNamedQuery("Question.findByPuzzleId");
//            query.setParameter("puzzleId", puzzleId);
//
//            return query.getResultList();
            temp = findQuestionEntities();
            for (int i= 0; i < temp.size(); i++) {
                if (temp.get(i).getPuzzle().getPuzzleId() == puzzleId) {
                    lst.add(temp.get(i));
                }
            }

            return lst;
        } catch (Exception e) {
            Logger.getLogger(QuestionJpaController.class.getName()).log(java.util.logging.Level.SEVERE, null, e);
            return null;
        }
    }

    /**
     * getQuestionByQuestionContent
     * @param quest
     * @return Question
     */
    public Question getQuestionByQuestionContent(String quest) {
        Question question = null;
        try {
            try {
                Query query = getEntityManager().createNamedQuery("Question.findByQuestion");
                query.setParameter("question", quest);

                question = (Question) query.getSingleResult();
            } catch (Exception e) {
            }
        } catch (Exception e) {
            while (question == null) {
                try {
                    Query query = getEntityManager().createNamedQuery("Question.findByQuestion");
                    query.setParameter("question", quest);

                    question = (Question) query.getSingleResult();
                } catch (Exception ex) {
                }
            }
            Logger.getLogger(QuestionJpaController.class.getName()).log(java.util.logging.Level.SEVERE, null, e);
        }
        return question;
    }
}
